# coding=utf-8
__author__ = 'Administrator'
import json
from django.db.models import DateTimeField, DateField, CommaSeparatedIntegerField, ImageField, DecimalField, CharField
from django.db import models

BASE_DATE_FORMAT = '%Y-%m-%d'
BASE_DATETIME_FORMAT = '%Y-%m-%d $H:%M:%S'


class JSONBaseMixin(object):
    """
    models json 序列化掺和类
    """

    def toJSON(self):
        fields = []
        for field in self._meta.fields:
            fields.append(field.name, field.attname, type(field))

        d = {}
        for attr,attname,t in fields:
            if getattr(self,attname,None) == None:
                d[attr] = None
            else:
                if t==DateTimeField and not isinstance(getattr(self,attname),(str,unicode)):
                    try:
                        d[attr] = getattr(self,attname).strftime(BASE_DATE_FORMAT)
                    except:
                        d[attr] = '2015-12-29 09:23:30'
